

export default function useColumnWidth() {

  const getTextWidth = (text: string, font: string = '14px Arial'): number => {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    if (context) {
      context.font = font;
      return context.measureText(text).width;
    }
    return 0;
  }

  const flexColumnWidth = (str: string,
    tableData: Array<Record<string, any>>,
    flag: 'max' | 'equal' = 'max'): string | undefined => {
    if (!tableData || !tableData.length || !str) return;
    // console.log(tableHeader,'tableHeader');
   
    

    let columnContent = '';
    if (flag === 'equal') {
      for (let i = 0; i < tableData.length; i++) {
        const content = tableData[i][str];
        if (content && content.length > 0) {
          columnContent = content;
          break;
        }
      }
    } else {
      let index = 0;
      for (let i = 0; i < tableData.length; i++) {
        const now_temp = tableData[i][str] ? tableData[i][str].toString() : '';
        const max_temp = tableData[index][str] ? tableData[index][str].toString() : '';
        if (now_temp.length > max_temp.length) index = i;
      }
      columnContent = tableData[index][str]?.toString() || '';
    }

    if (!columnContent) return;

    const font = '14px Arial';
    let textWidth = getTextWidth(columnContent, font);
    const padding = 24 + 2;
    const totalWidth = Math.ceil(textWidth + padding);

    if (totalWidth < 100) return '100px';
    return `${totalWidth}px`;
  }

  return {
    flexColumnWidth
  }
}
